//
//  playVoiceViewController.m
//  AIM
//
//  Created by user10 on 2017/8/2.
//  Copyright © 2017年 user10. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "playVoiceViewController.h"
#import "RecordAudio.h"

@interface playVoiceViewController ()<RecordAudioDelegate>
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;

@property (nonatomic, strong)RecordAudio *recordAudio;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic, strong)NSString *flag;
@property (nonatomic, strong)MPVolumeView *volumeView;
@property (nonatomic, strong)UISlider *tmpSlider;
@end

@implementation playVoiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    RecordAudio *recordAudio = [[RecordAudio alloc]init];
    recordAudio.delegate = self;
    if ([self isHeadsetPluggedIn]) {
        [recordAudio.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
        
        [recordAudio.audioSession setActive:YES error: nil];
    }else{
        [recordAudio.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        
        [recordAudio.audioSession setActive:YES error: nil];
    }
    _recordAudio = recordAudio;
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    _volumeView = volumeView;
    UISlider *tmpSlider = [[UISlider alloc]init];
    _tmpSlider = tmpSlider;
    
    _slider.value = [[AVAudioSession sharedInstance] outputVolume];
    // send UI control event to make the change effect right now.
    [_tmpSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(volumeChanged:)
     
                                                 name:@"AVSystemController_SystemVolumeDidChangeNotification"
     
                                               object:nil];
    
    _flag = @"1";
    
    NSLog(@"%@",[self isHeadsetPluggedIn]?@"yes":@"no");
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)   name:AVAudioSessionRouteChangeNotification object:nil];
    [_slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
}

//判断耳机是否已经插入
- (BOOL)isHeadsetPluggedIn {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        NSLog(@"%@",[desc portType]);
        if ([[desc portType] isEqualToString:@"Headphones"])
            return YES;
    }
    return NO;
}

- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            [_recordAudio.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
            //Activate the session

            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            
            [_recordAudio.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];

            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}

- (void)volumeChanged:(NSNotification *)noti{
    NSDictionary *interuptionDict = noti.userInfo;
    float value = [[interuptionDict valueForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
    
    _slider.value = value;
}

- (IBAction)sliderValueChanged:(id)sender {
    
    for (UIView *view in [_volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            _tmpSlider = (UISlider*)view;
            break;
        }
    }
    
    // send UI control event to make the change effect right now.
    [_tmpSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
    
    UISlider *slider = (UISlider *)sender;
    
    [_tmpSlider setValue:slider.value animated:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)playVoice:(id)sender {
    if ([_flag isEqualToString:@"1"]) {
        
        [_recordAudio play:_voiceData];
        [_playBtn setImage:[UIImage imageNamed:@"stop23"] forState:UIControlStateNormal];
        _flag = @"2";
    }else{
        [_recordAudio stopPlay];
        
        [_playBtn setImage:[UIImage imageNamed:@"play48"] forState:UIControlStateNormal];

        _flag = @"1";
    }
}
-(void)RecordStatus:(int)status{
    if (1 == status) {
        [_playBtn setImage:[UIImage imageNamed:@"play48"] forState:UIControlStateNormal];
        
        _flag = @"1";
    }
}
- (IBAction)closeVoiceView:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
